import {
  LoginLayout,
  MInput,
  MModal,
} from '@/views/login/components/LoginContainer.jsx';
import styled from 'styled-components';
import {Checkbox, Form, Input, message, Select} from 'antd';

const {Option} = Select;
import {useRef, useState} from 'react';
import {register, sendSmscode} from '@/api/user.js';
import {getImageUrl, debounce} from '@/utils/utils.js';
import _ from 'lodash';
import {b64_md5} from '@/utils/md5Ver2.2.js';
import {useNavigate} from 'react-router-dom';

const {TextArea} = Input;
const RegisterContainer = styled.div`
    width: 480px;
    height: 792px;
    background: #fff;
    box-shadow: 0 0 25px #99989826;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    box-sizing: border-box;
    padding: 41px 51px 35px 51px;
    border-radius: 25px;
    overflow-y: auto;

    &::-webkit-scrollbar {
        display: none;
    }

    -ms-overflow-style: none; /* IE 和 Edge */
    scrollbar-width: none; /* Firefox */


    .code {
        color: #53b332;
        font-size: 14px;
        font-weight: 400;
        line-height: 12px;
        cursor: pointer;
    }

    .ant-select-selector {
        background: #F5F9FE !important;
        border: none !important;
        //height: 56px !important;
        box-shadow: none !important;
        //line-height: 56px !important;
        padding: 6px 20px !important;
        font-size: 14px;
    }

    .ant-select-selector::placeholder {
        color: #666666;
        font-size: 14px;
        font-weight: 400;
    }

    .ant-select-single {
        height: 56px !important;
    }

    .ant-select-selection-placeholder {
        color: #666666 !important;
        font-size: 14px;
        font-weight: 400;
    }

    .ant-input {
        height: 56px;
        font-size: 14px;
        border: none !important;
        box-shadow: none !important;
        background: #F5F9FE !important;
    }

    .ant-input::placeholder {
        color: #666666 !important;
        font-size: 14px;
        font-weight: 400;
    }

    .ant-form-item .ant-form-item-label > label {
        height: 56px;
        color: #1c1c1c;
        font-size: 18px;
        font-weight: 400;
    }

    .mTextArea {


        .ant-input-outlined {
            border: none;
            box-shadow: none !important;
        }

        .textArea-box {
            height: 149px;
            background: #F5F9FE !important;
            position: relative;
            display: flex;
            flex-direction: column;
            box-sizing: border-box;
            padding-bottom: 12px;
        }

        .count {
            color: #666666;
            font-size: 14px;
            font-weight: 400;
            line-height: 24px;
            text-align: end;
            padding-right: 12px;
        }

        .ant-input {
            flex: 1;
            //height: 149px;
            font-size: 14px;
            border: none !important;
            box-shadow: none !important;
            //background: #F5F9FE !important;
            border-radius: 10px;
            padding: 10px 10px 0px 10px;
        }


        //.ant-input-textarea-show-count .ant-input-data-count {
        //    right: 12px;
        //    bottom: 12px;
        //    background: #F5F9FE;
        //}
    }

    .ant-checkbox .ant-checkbox-inner {
        border: 1.29px solid #53B332;
        border-radius: 0;
    }

    .ant-checkbox-checked .ant-checkbox-inner {
        background: #53B332 !important;
    }

    .label {
        color: #666666;
        font-size: 14px;
        font-weight: 300;
    }

    .register-btn {
        width: 100%;
        height: 56px;
        opacity: 0.8;
        font-size: 22px;
        font-weight: 400;
        color: #fff;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        margin-top: 48px;
        background: linear-gradient(90deg, #06a0fd 0%, #37eab4 100%);

        &:hover {
            background: linear-gradient(90deg, #06a0fdce 0%, #37eab4ce 100%);
        }
    }

    .tips {
        color: #75c25b;
        font-size: 18px;
        font-weight: 400;
        line-height: 44px;
        text-align: center;
        margin-top: 30px;
        cursor: pointer;
    }

`;

function CodeBtn({isSendCode, countDown, sendCode}) {
  return (<>
    <div className="code" onClick={sendCode}>{isSendCode
        ? '发送验证码'
        : countDown + 's后可重新发送'}</div>
  </>);
}

function RegisterPage() {
  const [form] = Form.useForm();
  const formRef = useRef();
  const [isSendCode, setIsSendCode] = useState(true);
  const [countDown, setCountDown] = useState(60);
  const [isShowPwd, setIsShowPwd] = useState(true);
  const [isReShowPwd, setReIsShowPwd] = useState(true);
  const [checkProtocol, setCheckProtocol] = useState(false);
  const navigate = useNavigate();
  const [isShowModal, setIsShowModal] = useState(false);

  const password = Form.useWatch('password', form);
  const repassword = Form.useWatch('repassword', form);
  const role_type = Form.useWatch('role_type', form);
  const self_introduction = Form.useWatch('self_introduction', form);

  function handleCancel() {
    setIsShowModal(false);
    navigate('/login');
  }

  const sendCode = debounce(() => {
    if (!isSendCode) return;
    form.validateFields(['mobile']).then(async values => {
      // 验证通过
      const res = await sendSmscode(values.mobile, 2);
      if (res.result.status_info.status_code !== 100) {
        message.open({
          type: 'error',
          content: res.result.status_info.status_message,
        });
        return;
      }
      setIsSendCode(false);
      const timer = setInterval(() => {
        setCountDown((value) => {
          if (value === 0) {
            clearInterval(timer);
            setIsSendCode(true);
            return 60;
          }
          return value - 1;
        });
      }, 1000);
    }).catch(errorInfo => {
      // 验证失败
      console.log('验证失败:', errorInfo);
    });
  }, 200);

  const handleRegister = _.debounce(() => {
    if (!checkProtocol) return;
    form.validateFields().then(async values => {
      console.log(values);
      let params = {
        user_name: values.user_name,
        mobile: values.mobile,
        sms_code: values.code,
        password: b64_md5(values.password),
        role_type: values.role_type,
      };
      if (+role_type === 2) {
        params = {
          ...params,
          authentication_user_name: values.authentication_user_name,
          organization_name: values.organization_name,
          job_title: values.job_title,
          self_introduction: values.self_introduction,
        };
      }
      const res = await register(params);
      if (res.result.status_info.status_code !== 100) {
        message.open({
          type: 'error',
          content: res.result.status_info.status_message,
        });
        return;
      }
      setIsShowModal(true);
    }).catch(errorInfo => {
      // 验证失败
      console.log('验证失败:', errorInfo);
    });
  }, 200);

  return (<>
    <LoginLayout>
      <RegisterContainer>
        <Form
            colon={false}
            form={form}
            ref={formRef}>
          <Form.Item
              name="user_name"
              style={{marginBottom: '30px'}}
              validateTrigger="onBlur"
              rules={[
                {required: true, message: '请输入用户名称'},
              ]}
          >
            <MInput iconFontClass="icon-user" placeholder="请输入用户名称"
                    maxLength={12}></MInput>
          </Form.Item>
          <Form.Item
              name="mobile"
              style={{marginBottom: '30px'}}
              validateTrigger="onBlur"
              rules={[
                {required: true, message: '请输入有效的手机号码'},
                {
                  validator: (_, value) => {
                    // const notNumberReg = /[^\d]+/g
                    const mobileReg = /^1[3-9][\d]{9}$/g; //手机号验证正则表达式
                    // if (value && notNumberReg.test(value)) {
                    //   form.setFieldValue(['mobile'], value.replace(notNumberReg, ''))
                    //   return Promise.reject(new Error('请输入有效的手机号码'));
                    // }
                    if (value && !mobileReg.test(value)) {
                      return Promise.reject(new Error('请输入有效的手机号码'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
          >
            <MInput iconFontClass="icon-phone" placeholder="请输入手机号码"
                    maxLength={11}></MInput>
          </Form.Item>
          <Form.Item
              name="code"
              validateTrigger="onBlur"
              style={{marginBottom: '30px'}}
              rules={[
                {required: true, message: '验证码不能为空'},
                {
                  validator: (_, value) => {
                    // const notNumberReg = /[^\d]+/g
                    const vertificationCodeReg = /^[\d]{6}$/g; //验证码验证正则表达式
                    // if (value && notNumberReg.test(value)) {
                    //   form.setFieldValue(['code'], value.replace(notNumberReg, ''))
                    //   return Promise.reject(new Error('您输入的验证码错误，请重新输入'));
                    // }
                    if (value && !vertificationCodeReg.test(value)) {
                      return Promise.reject(
                          new Error('您输入的验证码错误，请重新输入'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
          >
            <MInput iconFontClass="icon-message" placeholder="请输入短信验证码"
                    maxLength={6}
                    suffix={<CodeBtn isSendCode={isSendCode}
                                     countDown={countDown}
                                     sendCode={sendCode}/>}></MInput>
          </Form.Item>
          <Form.Item
              name="password"
              style={{marginBottom: '30px'}}
              validateTrigger="onBlur"
              rules={[
                {required: true, message: '密码不能为空字符'},
                {
                  validator: (_, value) => {
                    const passwordReg = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,20}$|^(?=.*[a-zA-Z])(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,20}$|^(?=.*[0-9])(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?])[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,20}$/; //手机号验证正则表达式
                    if (value && !passwordReg.test(value)) {
                      return Promise.reject(new Error(
                          '格式错误，需含数字、字母和符号中至少2种，8-20位'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
          >
            <MInput iconFontClass="icon-lock"
                    placeholder="请设置密码（8-20位，数字＋字母或符号）"
                    type={isShowPwd ? 'password' : 'text'} suffix={password &&
                <img src={getImageUrl(
                    isShowPwd ? 'ic_eye_stop.png' : 'ic_eye.png')}
                     style={{width: '20px', height: '20px', cursor: 'pointer'}}
                     onClick={() => {
                       setIsShowPwd(!isShowPwd);
                     }}/>}></MInput>
          </Form.Item>
          <Form.Item
              name="repassword"
              style={{marginBottom: '30px'}}
              validateTrigger="onBlur"
              rules={[
                {required: true, message: '密码不能为空字符'},
                {
                  validator: (_, value) => {
                    const fPass = form.getFieldValue('password');
                    if (fPass !== value && value) {
                      return Promise.reject(new Error('两次输入密码不一致'));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
          >
            <MInput iconFontClass="icon-lock" placeholder="请再次输入密码"
                    type={isReShowPwd ? 'password' : 'text'}
                    suffix={repassword &&
                        <img src={getImageUrl(
                            isReShowPwd ? 'ic_eye_stop.png' : 'ic_eye.png')}
                             style={{
                               width: '20px',
                               height: '20px',
                               cursor: 'pointer',
                             }} onClick={() => {
                          setReIsShowPwd(!isReShowPwd);
                        }}/>}></MInput>
          </Form.Item>
          <Form.Item
              name="role_type"
              rules={[
                {
                  required: true,
                  message: '请选择你的角色',
                },
              ]}
          >
            <Select placeholder="请选择你的角色" allowClear={true}>
              <Option value="1">普通读者</Option>
              <Option value="2">报刊社职工（需认证信息）</Option>
            </Select>
          </Form.Item>
          {+role_type === 2 && <Form.Item name="authentication_user_name"
                                          label="姓名"
                                          style={{marginBottom: '30px'}}

                                          validateTrigger="onBlur"
                                          rules={[
                                            {
                                              required: true,
                                              message: '姓名不能为空',
                                            },
                                          ]}>
            <Input placeholder="限12字" maxLength={12}/>
          </Form.Item>}
          {
              +role_type === 2 && <Form.Item name="organization_name"
                                             label="单位"
                                             style={{marginBottom: '30px'}}

                                             validateTrigger="onBlur"
                                             rules={[
                                               {
                                                 required: true,
                                                 message: '单位不能为空',
                                               },
                                             ]}>
                <Input placeholder="限100字" maxLength={12}/>
              </Form.Item>
          }
          {
              +role_type === 2 && <Form.Item name="job_title"
                                             label="职位"
                                             style={{marginBottom: '30px'}}

                                             validateTrigger="onBlur"
                                             rules={[
                                               {
                                                 required: true,
                                                 message: '职位不能为空',
                                               },
                                             ]}>
                <Input placeholder="限100字" maxLength={12}/>
              </Form.Item>
          }
          {
              +role_type === 2 && <Form.Item name="self_introduction"
                                             label="基本介绍"
                                             className={'mTextArea'}
                                             style={{
                                               marginBottom: '30px',
                                               marginLeft: '-25px',
                                             }}>
                <div className={'textArea-box'}>
                  <TextArea rows={4} maxLength={200} showCount={false}
                            style={{resize: 'none'}}/>
                  <div className={'count'}>{200 -
                      (self_introduction?.length || 0)}</div>
                </div>
              </Form.Item>
          }
          <Checkbox checked={checkProtocol} onChange={(e) => {
            setCheckProtocol(e.target.checked);
          }}><span className="label">勾选同意</span></Checkbox> <span
            style={{color: '#75C25B', cursor: 'pointer'}}
            onClick={() => {
              navigate('/userProtocol');
            }}>《用户服务协议》</span>
          <div className="register-btn" onClick={handleRegister}
               style={{cursor: checkProtocol ? 'pointer' : 'not-allowed'}}>注册
          </div>
          <div className={'tips'} onClick={() => {
            navigate('/login');
          }}>已有账号，立即登录
          </div>
        </Form>
      </RegisterContainer>
      {isShowModal &&
          <MModal isModalOpen={isShowModal} handleCancel={handleCancel}
                  title="恭喜您注册成功"
                  tips="请妥善保管您的账户信息" btnText="登录"
                  isInternal={true}/>}
    </LoginLayout>
  </>);
}

export default RegisterPage;